package hibernate.dao;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

import org.springframework.orm.hibernate3.HibernateTemplate;

public class BasicDAOImpl implements BasicDAO {
	HibernateTemplate hibernateTemplate;
	
	BasicDAOImpl(){
		System.out.println("BasicDAOImpl create!");
	}
	
	public <T> T getEntity(Class<T> entityClass, Serializable id) {
		T obj = hibernateTemplate.get(entityClass, id);
		return obj;
	}
	public  boolean addEntity(Object entity) throws Exception{
			hibernateTemplate.saveOrUpdate(entity);
//			throw new Exception("I have throw a exception!!!!!");
		return true;
	}
	
	public boolean deleteEntity(Class<?> entity, Serializable id){
		try{
			hibernateTemplate.delete(hibernateTemplate.get(entity, id));
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public Object updateEntity(Object entity){
		Object obj = null;
		try {
			obj = hibernateTemplate.merge(entity);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		return obj;
	}
	
	@SuppressWarnings("unchecked")
	public <T> List<T> getResultList(Class<T> entityClass, String whereStr, LinkedHashMap<String, String> orderBy){
		String tName = entityClass.getSimpleName();
		List<T> resultList = (List<T>)hibernateTemplate.find("from " + tName + " as o " + whereStr + this.getOrderBy(orderBy));
		return resultList;
	}
	
	
	private String getOrderBy(LinkedHashMap<String, String> orderBy){
		//first word place the column name;
		//last word place the sortting method
		StringBuffer headStr = new StringBuffer(" order by ");
		Set<String> keys = orderBy.keySet();
		for(String key:keys){
			String sortMethod = orderBy.get(key);
			headStr.append(key+" "+sortMethod);
		}
		return headStr.toString();
	}
	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		System.out.println("hibernateTemplate-->BasicDAOImpl");
		this.hibernateTemplate = hibernateTemplate;
	}
	
}
